<template>
	<div class="scene-container">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="业务场景管理" name="scene">
				<MessageTips @ok="tipsOk" @close="tipsClose" @cancel="tipsCancel" :messageInfo="messageInfo" />
				<Search @searchData="searchBusinessScence" />
				<div class="head">
					<el-button type="primary" @click="addScene">新增</el-button>
				</div>
				<Table :tableData="tableData">
					<template v-slot:status>
						<el-table-column align="center" label="业务状态">
							<template slot-scope="scope">
								<p>{{ scope.row.sceneStatus ? '启用' : '停用' }}</p>
							</template>
						</el-table-column>
					</template>
					<template v-slot:btn>
						<el-table-column width="310px" align="center" label="编辑业务">
							<template slot-scope="scope">
								<el-button size="mini" class="set-btn" :class="scope.row.sceneStatus ? 'disabled' : ''" :disabled="scope.row.sceneStatus" @click="modifyScene(scope.row)"
									>编辑</el-button
								>
								<el-button size="mini" class="set-btn" @click="setScene(scope.row)">配置业务属性</el-button>
								<el-button size="mini" class="open-btn" v-if="!scope.row.sceneStatus" @click="changeStatus(scope.row)">启用</el-button>
								<el-button size="mini" class="stop-btn" v-else @click="changeStatus(scope.row)">停用</el-button>
							</template>
						</el-table-column>
					</template>
				</Table>
				<div class="page">
					<PageSize :pages="searchData" @changePageSize="changeScenePageSize" @changeCurrentPage="changeSceneCurrentPage" />
				</div>
				<AddScene :showAddScene="showAddScene" v-if="showAddScene" @closeAddScene="closeAddScene" @sureAddScene="sureAddScene" />
				<ModifyScene :showEditScene="showEditScene" v-if="showEditScene" :editSceneData="editSceneData" @closeEditScene="closeEditScene" @sureEditScene="sureEditScene" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
import MessageTips from '../components/MessageTips.vue';
import Search from '../components/Search.vue';
import Table from '../components/Table.vue';
import AddScene from './AddScene.vue';
import ModifyScene from './ModifyScene.vue';
import PageSize from '../components/PageSize.vue';
import { mapState, mapMutations } from 'vuex';
import { getBusinessScenceList, createBusinessScence, updateBusinessScence, startBusinessScence } from '../../api/api';
export default {
	components: {
		MessageTips,
		Search,
		Table,
		AddScene,
		ModifyScene,
		PageSize
	},
	data() {
		return {
			activeName: 'scene',
			messageInfo: {
				isShow: false,
				title: '',
				content: ''
			},
			tableData: {
				sort: false,
				tableHead: [
				{
						label: 'id',
						prop: 'id'
					},
					{
						label: '业务场景名称',
						prop: 'sceneName'
					},
					{
						label: '创建时间',
						prop: 'createdAt'
					},
					{
						label: '创建人ID',
						prop: 'createdUserId'
					}
				],
				tableConent: [],
				showIndex: false,
				showCheck: false
			},
			currentScene: null,
			showAddScene: false,
			showEditScene: false,
			// 修改场景数据
			editSceneData: {},
			// 条件搜索
			searchData: {
				name: '',
				startTime: '',
				endTime: '',
				creator: '',
				page: 1,
				pageSize: 10,
				total: 0
			},
			editSceneId: null
		};
	},
	mounted() {
		this.getBusinessScenceListInit();
	},
	computed: {
		...mapState({
			sceneList: state => state.sceneInfo.sceneList,
			currentSceneStatus: state => state.sceneInfo.currentSceneStatus
		})
	},
	methods: {
		...mapMutations('menu', ['SET_TAG_LIST', 'SET_CACHE_VIEW', 'SET_SCENE_DATA', 'SET_SCENE_LIST', 'SET_SCENE_STATUS']),
		// 获取业务场景列表
		getBusinessScenceListInit() {
			getBusinessScenceList(this.searchData)
				.then(res => {
					if (res.status === 200) {
						this.searchData.total = res.data.count;
						const list = res.data.scenList.map(item => {
							return {
								id: item.id,
								sceneName: item.name,
								sceneStatus: item.status,
								createdUserId: item.creator,
								org: item.org,
								createdAt: this.$moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss')
							};
						});
						console.log(list);
						this.$store.commit('SET_SCENE_LIST', list);
						this.tableData.tableConent = this.sceneList;
					}
				})
				.catch(err => {
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		// 提示框确认
		tipsOk() {
			let data = {};
			data.id = this.currentScene.id;
			data.state = !this.currentScene.sceneStatus;
			startBusinessScence(data)
				.then(res => {
					if (res.status === 200) {
						this.getBusinessScenceListInit();
					}
				})
				.then(() => {
					this.$message.success(`业务场景${data.state ? '启用' : '停用'}成功！`);
				})
				.catch(err => {
					if (err.data && err.data.errCode) {
						switch (err.data.errCode) {
							case 1:
								this.$message.error('该业务场景尚未完成派工规则配置，不可启用！');
								break;
							case 2:
								this.$message.error('该业务场景尚未完成坐席技能组配置，不可启用！');
								break;
							case 3:
								this.$message.error(`该技能组所属业务没有绑定AI工作流，请先为业务场景<${this.currentScene.sceneName}>绑定AI工作流！`);
								break;
							case 4:
								this.$message.error('该业务下存在通话');
								break;
							case 5:
								this.$message.error('启用失败，当前场景中AI坐席工作流存在错误，请检查后重新启用！');
								break;
							default:
								this.$message.error(`业务场景${data.state ? '启用' : '停用'}失败！`);
								break;
						}
					} else {
						this.$message.error(`业务场景${data.state ? '启用' : '停用'}失败！`);
					}
					this.getBusinessScenceListInit();
				});
			this.messageInfo.isShow = false;
		},
		// 提示框关闭
		tipsClose() {
			this.messageInfo.isShow = false;
		},
		// 提示框取消
		tipsCancel() {
			this.messageInfo.isShow = false;
		},
		// 检索数据
		searchBusinessScence(data) {
			console.log(data);
			this.searchData.name = data.name;
			this.searchData.startTime = data.startTime;
			this.searchData.endTime = data.endTime;
			this.searchData.creator = data.createPersonId;
			this.searchData.page = 1;
			this.searchData.pageSize = 10;
			this.getBusinessScenceListInit();
		},
		// 改变业务类型状态
		changeStatus(row) {
			this.messageInfo.isShow = true;
			this.messageInfo.title = `${row.sceneStatus ? '停用' : '启用'}业务场景`;
			this.messageInfo.content = `确定${row.sceneStatus ? '停用' : '启用'} < ${row.sceneName} > 吗？`;
			this.currentScene = row;
		},
		// 修改业务场景名称
		modifyScene(row) {
			this.editSceneData = row;
			this.showEditScene = true;
			this.editSceneId = row.id;
		},
		// 关闭修改模态框
		closeEditScene() {
			this.showEditScene = false;
		},
		// 确认修改
		sureEditScene(data) {
			this.showEditScene = false;
			updateBusinessScence(this.editSceneId, data)
				.then(() => {
					this.$message.success('修改成功');
					this.getBusinessScenceListInit();
					this.showEditScene = false;
				})
				.catch(err => {
					if (err.code === 1002) {
						this.$message.error('该场景名称已被使用，请重新编辑！');
					} else {
						this.$message.error('修改业务场景名称失败');
					}
				});
		},

		// 新增业务场景
		addScene() {
			this.showAddScene = true;
		},
		// 关闭新增模态框
		closeAddScene() {
			this.showAddScene = false;
		},

		// 配置业务属性
		setScene(row) {
			sessionStorage.setItem('sceneData', JSON.stringify(row));
			let menu = {
				meta: {}
			};
			console.log(row);
			const { meta, name, path } = this.$route;
			menu.name = `${name}/${row.id}`;
			menu.meta.jumpNo = meta.jumpNo + 1;
			menu.meta.sceneName = row.sceneName;
			menu.meta.keepAlive = false;
			menu.meta.title = `${row.sceneName}详情`;
			menu.meta.data = row;
			menu.meta.toPath = `${meta.toPath}/sceneInfo/${row.id}`;
			menu.path = `${path}/${row.id}`;
			this.$store.commit('SET_TAG_LIST', menu);
			this.$store.commit('SET_SCENE_STATUS', row.sceneStatus);
			localStorage.setItem('sceneStatus', row.sceneStatus);
			console.log(row.sceneStatus);
			this.$router.push({ name: 'sceneInfo', meta: menu.meta, params: { id: row.id, title: menu.meta.title } });
		},

		// 新增业务场景
		sureAddScene(data) {
			console.log(data);
			createBusinessScence(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('新增业务场景成功！');
					} else if (res.status === 409) {
						this.$message.error('该场景名称已被使用！');
					}
					this.getBusinessScenceListInit();
				})
				.catch(err => {
					this.$message.error(`新增业务场景失败！${err}`);
				});
			this.showAddScene = false;
		},
		// 分页
		changeScenePageSize(val) {
			this.searchData.pageSize = val;
			this.searchData.page = 1;
			console.log(this.searchData);
			this.getBusinessScenceListInit();
		},
		changeSceneCurrentPage(val) {
			this.searchData.page = val;
			// todo  请求了两次接口， 页码翻页刷新每次都是10条/页
			// this.searchData.pageSize = 10;
			this.getBusinessScenceListInit();
		}
	}
};
</script>

<style lang="less">
.scene-container {
	.el-table thead {
		color: #676a6c;
		tr {
			th {
				background-color: #f8f8f9;
			}
		}
	}
	.page {
		margin-top: 20px;
	}
}
</style>

<style lang="less" scoped>
.scene-container {
	.head {
		padding-bottom: 20px;
		.el-button {
			width: 84px;
			height: 36px;
			background-color: #6384fe;
			padding: 0;
		}
	}
	.open-btn {
		background-color: #e6a23c;
		color: #fff;
	}
	.stop-btn {
		color: #fff;
		background-color: #ef5753;
	}
	.set-btn {
		color: #fff;
		background-color: #6384fe;
	}
	.disabled {
		background-color: #999;
	}
}
</style>
